import { 
  mockCases, 
  mockContracts, 
  mockClients, 
  mockDocuments, 
  mockFinanceRecords, 
  mockUserList,
  generateId,
  generateDate
} from './data'

// 模拟网络延迟
const delay = (ms: number = 300) => new Promise(resolve => setTimeout(resolve, ms))

// 分页工具函数
const paginate = <T>(data: T[], page: number, size: number) => {
  const start = (page - 1) * size
  const end = start + size
  return {
    list: data.slice(start, end),
    total: data.length,
    page,
    size,
    totalPages: Math.ceil(data.length / size)
  }
}

// 搜索过滤函数
const filterByKeyword = <T extends Record<string, any>>(data: T[], keyword: string, fields: string[]) => {
  if (!keyword) return data
  return data.filter(item => 
    fields.some(field => 
      String(item[field] || '').toLowerCase().includes(keyword.toLowerCase())
    )
  )
}

// 案件相关API
export const mockCaseAPI = {
  // 获取案件列表
  getList: async (params: any) => {
    await delay()
    let filteredData = [...mockCases]
    
    // 关键词搜索
    if (params.keyword) {
      filteredData = filterByKeyword(filteredData, params.keyword, ['title', 'caseNumber', 'clientName'])
    }
    
    // 状态筛选
    if (params.status) {
      filteredData = filteredData.filter(item => item.status === params.status)
    }
    
    // 优先级筛选
    if (params.priority) {
      filteredData = filteredData.filter(item => item.priority === params.priority)
    }
    
    const result = paginate(filteredData, params.page || 1, params.size || 20)
    return { code: 200, data: result, message: '获取成功' }
  },
  
  // 获取案件详情
  getDetail: async (id: string) => {
    await delay()
    const caseItem = mockCases.find(item => item.id === id)
    if (!caseItem) {
      throw new Error('案件不存在')
    }
    
    return {
      code: 200,
      data: {
        case: caseItem,
        progressList: [
          {
            id: '1',
            title: '案件立案',
            content: '案件已正式立案，分配给张律师负责',
            operatorName: '系统管理员',
            createdAt: generateDate(30)
          },
          {
            id: '2',
            title: '证据收集',
            content: '已收集相关证据材料，准备进入调查阶段',
            operatorName: '张律师',
            createdAt: generateDate(25)
          }
        ],
        documentList: mockDocuments.filter(doc => doc.caseTitle === caseItem.title),
        contractList: mockContracts.filter(contract => contract.clientId === caseItem.clientId)
      },
      message: '获取成功'
    }
  },
  
  // 创建案件
  create: async (data: any) => {
    await delay()
    const newCase = {
      id: generateId(),
      caseNumber: `CASE${new Date().getFullYear()}${String(mockCases.length + 1).padStart(3, '0')}`,
      ...data,
      createdAt: generateDate(0),
      updatedAt: generateDate(0)
    }
    mockCases.unshift(newCase)
    return { code: 200, data: newCase, message: '创建成功' }
  },
  
  // 更新案件
  update: async (id: string, data: any) => {
    await delay()
    const index = mockCases.findIndex(item => item.id === id)
    if (index === -1) {
      throw new Error('案件不存在')
    }
    mockCases[index] = { ...mockCases[index], ...data, updatedAt: generateDate(0) }
    return { code: 200, data: mockCases[index], message: '更新成功' }
  },
  
  // 删除案件
  delete: async (id: string) => {
    await delay()
    const index = mockCases.findIndex(item => item.id === id)
    if (index === -1) {
      throw new Error('案件不存在')
    }
    mockCases.splice(index, 1)
    return { code: 200, data: null, message: '删除成功' }
  }
}

// 合同相关API
export const mockContractAPI = {
  // 获取合同列表
  getList: async (params: any) => {
    await delay()
    let filteredData = [...mockContracts]
    
    if (params.keyword) {
      filteredData = filterByKeyword(filteredData, params.keyword, ['title', 'contractNumber', 'clientName'])
    }
    
    if (params.status) {
      filteredData = filteredData.filter(item => item.status === params.status)
    }
    
    const result = paginate(filteredData, params.page || 1, params.size || 20)
    return { code: 200, data: result, message: '获取成功' }
  },
  
  // 获取合同详情
  getDetail: async (id: string) => {
    await delay()
    const contract = mockContracts.find(item => item.id === id)
    if (!contract) {
      throw new Error('合同不存在')
    }
    
    return {
      code: 200,
      data: {
        contract,
        clauses: [
          { title: '第一条 合同目的', content: '本合同旨在明确双方在服务提供过程中的权利义务关系' },
          { title: '第二条 服务内容', content: '乙方应按照约定提供专业的法律服务' },
          { title: '第三条 费用支付', content: '甲方应按照约定时间支付服务费用' }
        ],
        approvalHistory: [
          {
            id: '1',
            action: '合同创建',
            comment: '合同初稿已创建',
            operatorName: '张律师',
            createdAt: generateDate(15)
          },
          {
            id: '2',
            action: '提交审核',
            comment: '合同已提交法务部审核',
            operatorName: '张律师',
            createdAt: generateDate(10)
          }
        ],
        documentList: mockDocuments.filter(doc => doc.contractTitle === contract.title),
        caseList: mockCases.filter(caseItem => caseItem.clientId === contract.clientId),
        financeSummary: {
          received: contract.amount * 0.6,
          pending: contract.amount * 0.4
        }
      },
      message: '获取成功'
    }
  },
  
  // 创建合同
  create: async (data: any) => {
    await delay()
    const newContract = {
      id: generateId(),
      contractNumber: `CT${new Date().getFullYear()}${String(mockContracts.length + 1).padStart(3, '0')}`,
      ...data,
      createdAt: generateDate(0),
      updatedAt: generateDate(0)
    }
    mockContracts.unshift(newContract)
    return { code: 200, data: newContract, message: '创建成功' }
  },
  
  // 更新合同
  update: async (id: string, data: any) => {
    await delay()
    const index = mockContracts.findIndex(item => item.id === id)
    if (index === -1) {
      throw new Error('合同不存在')
    }
    mockContracts[index] = { ...mockContracts[index], ...data, updatedAt: generateDate(0) }
    return { code: 200, data: mockContracts[index], message: '更新成功' }
  },
  
  // 删除合同
  delete: async (id: string) => {
    await delay()
    const index = mockContracts.findIndex(item => item.id === id)
    if (index === -1) {
      throw new Error('合同不存在')
    }
    mockContracts.splice(index, 1)
    return { code: 200, data: null, message: '删除成功' }
  },
  
  // 获取合同模板
  getTemplates: async () => {
    await delay()
    return {
      code: 200,
      data: [
        {
          id: '1',
          name: '服务合同模板',
          type: 'service',
          description: '标准服务合同模板',
          createdAt: generateDate(100)
        },
        {
          id: '2',
          name: '采购合同模板',
          type: 'purchase',
          description: '标准采购合同模板',
          createdAt: generateDate(90)
        }
      ],
      message: '获取成功'
    }
  }
}

// 客户相关API
export const mockClientAPI = {
  // 获取客户列表
  getList: async (params: any) => {
    await delay()
    let filteredData = [...mockClients]

    if (params.keyword) {
      filteredData = filterByKeyword(filteredData, params.keyword, ['clientName', 'contactPerson', 'phone', 'email'])
    }

    if (params.type) {
      // 转换前端传入的字符串类型为数字类型
      const typeMap: Record<string, number> = {
        'individual': 1,
        'company': 2,
        'organization': 3
      }
      const clientType = typeMap[params.type]
      if (clientType) {
        filteredData = filteredData.filter(item => item.clientType === clientType)
      }
    }

    if (params.status) {
      // 转换前端传入的字符串状态为数字状态
      const statusMap: Record<string, number> = {
        'active': 1,
        'inactive': 0
      }
      const clientStatus = statusMap[params.status]
      if (clientStatus !== undefined) {
        filteredData = filteredData.filter(item => item.status === clientStatus)
      }
    }

    const result = paginate(filteredData, params.page || 1, params.size || 20)
    return { code: 200, data: result, message: '获取成功' }
  },
  
  // 获取客户详情
  getDetail: async (id: string) => {
    await delay()
    const client = mockClients.find(item => item.id === id)
    if (!client) {
      throw new Error('客户不存在')
    }
    
    return {
      code: 200,
      data: {
        client,
        relatedCases: mockCases.filter(caseItem => caseItem.clientId === id),
        relatedContracts: mockContracts.filter(contract => contract.clientId === id)
      },
      message: '获取成功'
    }
  },
  
  // 创建客户
  create: async (data: any) => {
    await delay()
    const newClient = {
      id: generateId(),
      ...data,
      createdAt: generateDate(0),
      updatedAt: generateDate(0)
    }
    mockClients.unshift(newClient)
    return { code: 200, data: newClient, message: '创建成功' }
  },
  
  // 更新客户
  update: async (id: string, data: any) => {
    await delay()
    const index = mockClients.findIndex(item => item.id === id)
    if (index === -1) {
      throw new Error('客户不存在')
    }
    mockClients[index] = { ...mockClients[index], ...data, updatedAt: generateDate(0) }
    return { code: 200, data: mockClients[index], message: '更新成功' }
  },
  
  // 删除客户
  delete: async (id: string) => {
    await delay()
    const index = mockClients.findIndex(item => item.id === id)
    if (index === -1) {
      throw new Error('客户不存在')
    }
    mockClients.splice(index, 1)
    return { code: 200, data: null, message: '删除成功' }
  }
}

// 文档相关API
export const mockDocumentAPI = {
  // 获取文档列表
  getList: async (params: any) => {
    await delay()
    let filteredData = [...mockDocuments]

    if (params.keyword) {
      filteredData = filterByKeyword(filteredData, params.keyword, ['name'])
    }

    if (params.type) {
      filteredData = filteredData.filter(item => item.type === params.type)
    }

    if (params.category) {
      filteredData = filteredData.filter(item => item.category === params.category)
    }

    const result = paginate(filteredData, params.page || 1, params.size || 20)
    return { code: 200, data: result, message: '获取成功' }
  },

  // 删除文档
  delete: async (id: string) => {
    await delay()
    const index = mockDocuments.findIndex(item => item.id === id)
    if (index === -1) {
      throw new Error('文档不存在')
    }
    mockDocuments.splice(index, 1)
    return { code: 200, data: null, message: '删除成功' }
  },

  // 获取文档分类
  getCategories: async () => {
    await delay()
    return {
      code: 200,
      data: [
        { label: '合同模板', value: '合同模板' },
        { label: '案件材料', value: '案件材料' },
        { label: '财务文档', value: '财务文档' },
        { label: '客户资料', value: '客户资料' },
        { label: '法律文书', value: '法律文书' }
      ],
      message: '获取成功'
    }
  }
}

// 财务相关API
export const mockFinanceAPI = {
  // 获取财务记录列表
  getList: async (params: any) => {
    await delay()
    let filteredData = [...mockFinanceRecords]

    if (params.keyword) {
      filteredData = filterByKeyword(filteredData, params.keyword, ['description'])
    }

    if (params.type) {
      filteredData = filteredData.filter(item => item.type === params.type)
    }

    if (params.category) {
      filteredData = filteredData.filter(item => item.category === params.category)
    }

    if (params.startDate && params.endDate) {
      filteredData = filteredData.filter(item => {
        const itemDate = new Date(item.date)
        return itemDate >= new Date(params.startDate) && itemDate <= new Date(params.endDate)
      })
    }

    const result = paginate(filteredData, params.page || 1, params.size || 20)
    return { code: 200, data: result, message: '获取成功' }
  },

  // 创建财务记录
  create: async (data: any) => {
    await delay()
    const newRecord = {
      id: generateId(),
      ...data,
      createdAt: generateDate(0)
    }
    mockFinanceRecords.unshift(newRecord)
    return { code: 200, data: newRecord, message: '创建成功' }
  },

  // 更新财务记录
  update: async (id: string, data: any) => {
    await delay()
    const index = mockFinanceRecords.findIndex(item => item.id === id)
    if (index === -1) {
      throw new Error('记录不存在')
    }
    mockFinanceRecords[index] = { ...mockFinanceRecords[index], ...data }
    return { code: 200, data: mockFinanceRecords[index], message: '更新成功' }
  },

  // 删除财务记录
  delete: async (id: string) => {
    await delay()
    const index = mockFinanceRecords.findIndex(item => item.id === id)
    if (index === -1) {
      throw new Error('记录不存在')
    }
    mockFinanceRecords.splice(index, 1)
    return { code: 200, data: null, message: '删除成功' }
  },

  // 获取财务统计
  getStats: async () => {
    await delay()
    const totalIncome = mockFinanceRecords
      .filter(item => item.type === 'income')
      .reduce((sum, item) => sum + item.amount, 0)

    const totalExpense = mockFinanceRecords
      .filter(item => item.type === 'expense')
      .reduce((sum, item) => sum + item.amount, 0)

    return {
      code: 200,
      data: {
        totalIncome,
        totalExpense,
        totalProfit: totalIncome - totalExpense,
        recordCount: mockFinanceRecords.length,
        incomeRecords: mockFinanceRecords.filter(item => item.type === 'income').length,
        expenseRecords: mockFinanceRecords.filter(item => item.type === 'expense').length
      },
      message: '获取成功'
    }
  },

  // 获取收支趋势
  getTrend: async (params: any) => {
    await delay()
    const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    const income = months.map(() => Math.floor(Math.random() * 50000) + 10000)
    const expense = months.map(() => Math.floor(Math.random() * 30000) + 5000)

    return {
      code: 200,
      data: { months, income, expense },
      message: '获取成功'
    }
  }
}

// 用户相关API
export const mockUserAPI = {
  // 获取用户列表
  getList: async (params: any) => {
    await delay()
    let filteredData = [...mockUserList]

    if (params.keyword) {
      filteredData = filterByKeyword(filteredData, params.keyword, ['username', 'realName', 'email'])
    }

    if (params.role) {
      filteredData = filteredData.filter(item => item.role === params.role)
    }

    if (params.status) {
      filteredData = filteredData.filter(item => item.status === params.status)
    }

    const result = paginate(filteredData, params.page || 1, params.size || 20)
    return { code: 200, data: result, message: '获取成功' }
  },

  // 创建用户
  create: async (data: any) => {
    await delay()
    const newUser = {
      id: generateId(),
      ...data,
      createdAt: generateDate(0),
      updatedAt: generateDate(0)
    }
    mockUserList.unshift(newUser)
    return { code: 200, data: newUser, message: '创建成功' }
  },

  // 更新用户
  update: async (id: string, data: any) => {
    await delay()
    const index = mockUserList.findIndex(item => item.id === id)
    if (index === -1) {
      throw new Error('用户不存在')
    }
    mockUserList[index] = { ...mockUserList[index], ...data, updatedAt: generateDate(0) }
    return { code: 200, data: mockUserList[index], message: '更新成功' }
  },

  // 删除用户
  delete: async (id: string) => {
    await delay()
    const index = mockUserList.findIndex(item => item.id === id)
    if (index === -1) {
      throw new Error('用户不存在')
    }
    mockUserList.splice(index, 1)
    return { code: 200, data: null, message: '删除成功' }
  }
}
